from django.shortcuts import render, redirect, HttpResponse
import json
# 通过Ajax在django发送POST请求时免除 csrf_token认证，@csrf_exempt
from django.views.decorators.csrf import csrf_exempt
from app02 import models
from app02.utils.bootstrap import BootStrapModelForm
from app02.utils.pagination import Pagination

import random
from datetime import datetime
from django.http import JsonResponse


class orderModelFrom(BootStrapModelForm):
    class Meta:
        model = models.order
        # fields = "__all__"   所有
        exclude = ["oid", "admin"]  # 排除oid


def order_list(request):
    """ 订单列表  """
    queryset = models.order.objects.all().order_by("id")
    # 2.实例化分页对象
    page_object = Pagination(request, queryset)
    form = orderModelFrom
    context = {
        "form": form,
        "order_list": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """ 新建订单(ajax)  """
    form = orderModelFrom(data=request.POST)
    # print(request.session["info"]["id"])
    # 验证成功保存到数据库
    if form.is_valid():
        # 额外添加一些不是用户输入的值(自己计算出来)
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(100, 999))

        # 固定设置管理员ID
        # form.instance.admin_id = 当前登录系统管理员的ID
        form.instance.admin_id = request.session["info"]["id"]

        # 保存到数据中
        form.save()
        return HttpResponse(json.dumps({"status": True}))  # json学列化
    # 返回错误信息
    return HttpResponse(json.dumps({"status": False, "error": form.errors}))


def order_delete(request):
    """ 删除订单 """
    # print(request.GET.get("uid"))
    uid = request.GET.get("uid")
    exists = models.order.objects.filter(id=uid).exists()
    if not exists:
        return HttpResponse(json.dumps({"status": False, "error": "数据不存在！"}))
    models.order.objects.filter(id=uid).delete()
    return HttpResponse(json.dumps({"status": True}))


def order_detail(request):
    """ 根据ID获取订单详细 """
    uid = request.GET.get("uid")
    row_dict = models.order.objects.filter(id=uid).values("titleo", "price", "status").first()
    if not row_dict:
        return JsonResponse({"status": False, "error": "数据不存在！"})

    # 从数据库中获取到一个对象row_object
    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    """ 编辑订单 """
    uid = request.GET.get("uid")
    row_object = models.order.objects.filter(id = uid).first()
    if not row_object:
        return JsonResponse({"status": False, "tips": "数据不存在！编辑失败"})

    form = orderModelFrom(data = request.POST,instance = row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status":True})

    return JsonResponse({"status": False, "error": form.errors})